import * as Minio from 'tz-minio-upload_beta';
import { getToken } from '/@/utils/auth';
import { useMessage } from '/@/hooks/web/useMessage';
import {
  obsEndPoint,
  obsAccessKeyId,
  obsScretAccessKey,
  obsBucketName,
} from '/@/settings/minioSetting';
const { createMessage } = useMessage();

export const bucketName = obsBucketName;
export const server = obsEndPoint;
// 创建ObsClient实例  http://123.60.141.47:9009/  30840
export const obsClient = Minio.createMinioClient({
  endPoint: server,
  port: 9000,
  useSSL: false,
  accessKey: obsAccessKeyId, //'CqsIQwnmzi0j9vZnyuIN',
  secretKey: obsScretAccessKey, //'zuf+kgsdAGETDRPCnkPuAXDXXquPvPo0Uoa1cz96p5cY'
});

//判断是否存在桶
export const isHasBucket = async () => {
  const exists = await obsClient.bucketExists(bucketName);
  if (exists) {
    console.log('Bucket exists');
    return true;
  } else {
    console.log('Bucket does not exist');
    return false;
  }
};

//上传文件
export const putObject = async (
  file: any,
  key: string,
  progressCallback: (transferredAmount: number, totalAmount: number, totalSeconds: number) => void,
  callback: (result) => void,
) => {
  return new Promise(async (resolve) => {
    console.log(file, '接收文件流');
    try {
      // 通过 MinIO 上传文件

      //创建文件的put方法的url
      obsClient.presignedPutObject(bucketName, key, 24 * 60 * 60, (err, presignedUrl) => {
        if (err) {
          createMessage.error('服务器连接超时');
          return err;
        }
        const config = {
          file,
          filePutUrl: presignedUrl,
          customHeader: {
            'X-FILENAME': encodeURIComponent(file.name),
            'X-Access-Token': getToken(),
          },
          onUploadProgress: (e) => {
            console.log('onUploadProgress', e);
            // { progressEvent, uploadingFile }
            // const progress = (progressEvent.loaded / progressEvent.total).toFixed(2);
            progressCallback(
              e.progressEvent.loaded,
              e.progressEvent.total,
              e.progressEvent.timeStamp,
            );
          },
          onUploaded: (e) => {
            // { result, uploadedFile }
            console.log('onUploaded', e);
            resolve(e.result);
            console.log('上传成功', key);
            callback(e);
          },
          onError: ({ error, errorFile }) => {},
        };
        createUploadHttp(config);
      });
      // await obsClient.putObject(bucketName, key, buf, file.size, function (err, objInfo) {
      //   if (err) {
      //     return console.log(err); // err should be null
      //   }
      //   console.log('Success', objInfo);
      //   progressCallback(100, 100, 5);
      //   callback(null);
      // });
    } catch (error) {
      console.error('上传失败', error);
      resolve(null);
    }
  });
};

//获取桶内对象
export const getBucketList = async (callback) => {
  const data: any = [];
  const stream = await obsClient.listObjects(bucketName, '', true);
  stream.on('data', function (obj) {
    data.push(obj);
  });
  stream.on('end', function () {
    console.log(data);
    callback(data);
  });
  stream.on('error', function (err) {
    console.log(err);
  });
};

//下载文件
export const getObject = async (
  key: any,
  callback: (result) => {},
  // progressCallback: (transferredAmount: number, totalAmount: number, totalSeconds: number) => void,
) => {
  const check = await obsClient.getObject(bucketName, key);
  // let size = check.on('data', function (chunk) {
  //   size += chunk.length;
  //   console.log('data. data size = ' + size);
  // });
  check.on('end', function () {
    // console.log('End. Total size = ' + size);
    callback({ Content: { SignedUrl: check.url } });
  });
  check.on('error', function (err) {
    console.log('check-error', err);
  });
};

//删除文件
export const deleteObject = async (key: any, callback: (result) => {}) => {
  await obsClient.removeObject(bucketName, key);
  callback(null);
};

//创建上传文件的http
function createUploadHttp(config) {
  const { file, filePutUrl, customHeader, onUploadProgress, onUploaded, onError } = config;
  // const fileName = file.name;
  const http = new XMLHttpRequest();
  http.upload.addEventListener(
    'progress',
    (e) => {
      //监听http的进度。并执行进度监听函数
      onUploadProgress({
        progressEvent: e,
        uploadingFile: file,
      });
    },
    false,
  );

  http.onload = () => {
    if ((http.status === 200 && http.status < 300) || http.status === 304) {
      try {
        //监听http的完成事件，并执行上传完成的监听函数
        const result = http.responseURL;
        onUploaded({ result, uploadedFile: file });
      } catch (error) {
        //监听错误
        onError({ error, errorFile: file });
      }
    }
  };

  http.open('PUT', filePutUrl, true);
  //加入头信息
  Object.keys(customHeader).forEach((key, index) => {
    http.setRequestHeader(key, customHeader[key]);
  });
  http.send(file);
  return http; //返回该http实例
}
